<template>
  <el-container class="container">
    <el-header class="header">
      <span v-if="!params.customer">{{ detail.groupName }}</span>
      <el-tabs v-model="activeTab" class="customer-tabs" v-if="params.customer && params.talk_source == '2'">
        <el-tab-pane label="正在咨询" name="0"></el-tab-pane>
        <el-tab-pane label="我的订单" name="1"></el-tab-pane>
      </el-tabs>
    </el-header>
    <el-main class="main lum-scrollbar">
        <template v-if="!params.customer">
            <div class="list-item">
                <span class="item-tips">所在组织：</span>
                <span class="item-data">【这里是预留组织的信息】</span>
            </div>
            <div class="list-item">
                <span class="item-tips">用户等级：</span>
                <span class="item-data">【这里是预留等级的信息】</span>
            </div>
        </template>
        <template  v-if="!params.customer || activeTab == '1'">
            <div class="order-header">
                <div class="order-header-title">用户订单</div>
                <el-select v-if="orderList.length > 0" v-model="status" placeholder="订单状态" size="small" style="width:100px" clearable @change="orderStatusChange">
                    <el-option
                        v-for="item in filterList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </div>
            <!-- 用户订单 -->
            <div class="user-order" :style="{background: orderList.length < 1 ? 'var(--next-color-white)' : ''}">
                <el-scrollbar>
                    <!-- 商品订单 -->
                    <div v-if="orderList.length > 0" class="order-cell" v-for="item in orderList" :key="item.id">
                        <div class="top-status">
                            <p class="time">下单时间: {{ item.createTime }}</p>
                            <p class="status red">{{ getStatusText(item.status) }}</p>
                        </div>
                        <div class="goods-data" v-for="goods in item.orderItemList" :key="goods.id">
                            <el-image :src="goods.skuPic" fit="cover" style="width:70px;height:70px;"></el-image>
                            <div class="order-data">
                                <p class="order-title b_row">{{ goods.skuName }}</p>
                                <div class="order-bottom">
                                    <p class="price"><span class="unit">￥</span>{{ goods.skuPrice }}</p>
                                    <el-button size="small" type="primary" @click="handleOrderDetail(item)">发送订单</el-button>
                                </div>
                            </div> 
                        </div>
                    </div>
                    <!-- 付费咨询订单 -->
                    <div v-else-if="payGoldList.length > 0" class="payGold-cell" v-for="order in payGoldList" :key="order.id">
                        <div class="top-status">
                            <p class="time">创建时间：{{ order.createTime }}</p>
                        </div>
                        <div class="order-content">
                            <div class="content-cell">
                                <span>支出：</span>
                                <span>{{ order.realPrice  || '--' }}币</span>
                            </div>
                            <div class="content-cell">
                                <span>余额：</span>
                                <span>{{ order.balance  || '--' }}币</span>
                            </div>
                        </div>
                        <div class="option">
                            <el-button link type="primary" size="small" @click="checkDetail(order)">查看详情</el-button>
                        </div>
                    </div>
                    <el-empty v-else description="暂无订单" />
                </el-scrollbar>
            </div>
            <div class="page-block">
                <el-pagination small background :pager-count="5" layout="prev, pager, next" :total="total" :hide-on-single-page="true" @current-change="handlePageChange" />
            </div>
        </template>
        <!-- 正在咨询的商品 -->
        <!-- TO DO 条件判断:  [&& currentGoods.id]  这个条件是用来判断是否有正在咨询的商品-->
        <div v-if="!params.customer || activeTab == '0'">
            <div class="order-header">
                <div class="order-header-title">正在咨询</div>
            </div>
            <div class="user-order current-preview" style="background: var(--next-color-white)">
                <div class="goods-data">
                    <el-image :src="currentGoods.skuPic" fit="cover" style="width:70px;height:70px;"></el-image>
                    <div class="order-data">
                        <p class="order-title b_row">{{ currentGoods.skuName }}</p>
                        <div class="order-bottom">
                            <p class="price"><span class="unit">￥</span>{{ currentGoods.skuPrice }}</p>
                        </div>
                    </div> 
                </div>
            </div>
        </div>
        <!-- 本店的商品列表 -->
        <div class="shop-list" v-if="params.customer && activeTab == '0'">
            <div class="order-header">
                <div class="order-header-title">本店其他商品</div>
            </div>
            <div class="shop-list-item">
                <el-scrollbar v-if="shopList.length > 0">
                    <div class="shop-item" v-for="product in shopList" :key="product.id">
                        <el-image fit="cover" :src="product.skuImg" style="width:70px;height:70px;"></el-image>
                        <div class="shop-goods-data">
                            <p class="goods-title b-row">{{ product.skuName }}</p>
                            <div class="goods-bottom">
                                <p class="price"><span class="unit">￥</span>{{ product.skuPrice }}</p>
                                <el-button size="small" type="primary" @click="sendGoods(item)">发送商品</el-button>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
                <el-empty v-else description="暂无商品" />
            </div>
            <el-button plain type="default" v-if="showMoreBtn" size="small" style="margin: 10px auto 0; display: block;" @click="handleLoadGoods">加载更多</el-button>
        </div>
        <!-- 对方提交的需求表 -->
        <!-- TO DO && questionnaireList.length > 0 -->
        <div v-if="!params.customer">
            <div class="order-header">
                <div class="order-header-title">需求表（{{ questionnaireList.length }}）</div>
            </div>
            <div class="user-order" style="background: var(--next-color-white)">
                <div class="question-cell" @click="handleQuestionner(item)" v-for="item in questionnaireList" :key="item.id">
                    <p class="question-title">问卷名称</p>
                </div>
            </div>
        </div>
        <!-- 客服接入计时器 -->
        <div class="calculate-time" v-if="params.customer && params.talk_source  == '3'">
            <p class="calculate-title">计时器</p>
            <div class="calculate-progress">
                <div class="calculate-item">
                    <p class="item">{{ time.mm }}</p>
                    <span>:</span>
                    <p class="item">{{ time.ss }}</p>
                </div>
            </div>
        </div>
    </el-main>
    <user-card-detail v-model:show="showUserDetail" :user_id="user_id"></user-card-detail>
    <order-detail v-model:dialogDrawer="showOrderDetail" v-model:defaultForm="rowForm"></order-detail>
    <el-dialog v-model="goldOrderDialog" title="订单详情" width="400px">
        <el-form label-width="60px" :model="goldDetail" size="small">
            <el-form-item label="创建时间" prop="createTime">{{ goldDetail.createTime }}</el-form-item>
            <el-form-item label="对话时间" prop="startTime">{{ goldDetail.startTime }} ~ {{ goldDetail.endTime }}</el-form-item>
            <el-form-item label="时长" prop="allSeconds">{{ formateSeconds(goldDetail.allSeconds) }}分钟</el-form-item>
            <el-form-item label="单价" prop="unitPrice">{{ goldDetail.unitPrice }}币/分钟</el-form-item>
            <el-form-item label="应付" prop="allPrice">{{ goldDetail.allPrice }}/币</el-form-item>
            <el-form-item label="实付" prop="realPrice">{{ goldDetail.realPrice }}/币</el-form-item>
            <el-form-item label="余额" prop="balance">{{ goldDetail.balance }}/币</el-form-item>
        </el-form>
    </el-dialog>
  </el-container>
</template>

<script>
import { reactive, toRefs, onMounted, watch, computed, nextTick, onUnmounted } from 'vue'
import { useChatApi } from '/@/api/chat/index'
import { Search, Plus } from '@element-plus/icons-vue'
import detaultAvatar from '/@/assets/detault-avatar.jpg'
import { useOrderApi } from '/@/api/order/index'
import { orderModelStatus } from '/@/stores/order'
import OrderDetail from '/@/views/order/components/OrderDetail.vue'

export default {
    name: 'GroupCustomer',
    props: {
        groupId: {
            type: [String, Number],
            default: null,
        },
        talkSource: { // 2 商城咨询； 3 付费咨询
            type: [String, Number],
            default: null
        },
        params: {
           type: Object,
           default: () => {
            return {}
           } 
        }
    },
    components: {
        OrderDetail
    },
    setup(props, context) {
        const { groupId, talkSource, params } = toRefs(props)
        const chatApi = useChatApi()
        const orderApi = useOrderApi()
        const storeOrder = orderModelStatus() // 订单各类状态数据
        let interver = null // 计时器
        const state = reactive({
            detail: {
                groupName: '', // 群名
                visitCard: '', // 群名片 
            },
            members: [],
            inviteFriendBox: false,
            keywords: '',
            showUserDetail: false,
            user_id: null,
            orderList: [],
            page: 1,
            size: 4,
            status: -1,
            total: 0,
            leaderUserId: null,
            filterList: storeOrder.status,
            rowForm: {},
            showOrderDetail: false,
            currentGoods: {},
            questionnaireList: [], // 需求表
            payGoldList: [], // 金币支付订单
            goldDetail: {}, // 金币订单详情
            goldOrderDialog: false,  // 金币订单详情展示
            activeTab: null, // 客户咨询页面的菜单激活菜单
            shopList: [], // 商品列表
            loadMoreGoods: false, // 加载更多商品
            showMoreBtn: false,
            productPage: 1, // 商品分页
            time: { // 计时器
                hh: '00',
                mm: '00',
                ss: '00'
            },
            allSeconds: 0
        })
        // 获取订单状态
        const getStatusText = computed(() => {
            return (val) => {
                const result = state.filterList.find(item => {
                    return item.id == String(val)
                })
                return result ? result.name : ''
            }
        })
        const searchs = computed(() => {
            return state.keywords == ''
                ? state.members
                : state.members.filter(item => {
                    return (
                        item.nickname.match(state.keywords) != null ||
                        item.user_card.match(state.keywords) != null
                    )
                })
        })
        // 加载群组成员列表
        const loadMembers = () => {
            chatApi.ServeGetGroupMembers({
                group_id: groupId.value,
            }).then(res => {
                if (res.code == 0) {
                  state.members = res.data.sort((a, b) => {
                    return b.leader - a.leader
                  })
                  const leader = state.members.find(item => {
                    return item.leader == 2
                  })
                  state.leaderUserId = leader && leader.user_id
                  context.emit('group-info', {
                      group_id: state.members.groupId,
                      members_num: state.members.length,
                  })
                  loadOrder()
                }
            })
        }
        // 加载群信息
        const loadGroupDetail = () => {
            state.isEditRemark = false
            chatApi.ServeGroupDetail({
                group_id: groupId.value,
            }).then(res => {
                if (res.code == 0) {
                    let result = res.data
                    state.detail.groupName = result.group_name
                    state.detail.visitCard = result.visit_card
                }
            })
        }
        // 加载订单
        const loadOrder = () => {
            if(!state.leaderUserId) return
            if(talkSource.value == 2) {
                orderApi.getList({
                    pageNum: state.page,
                    pageSize: state.size,
                    memberId: state.leaderUserId,
                    status: state.status
                }).then(res => {
                    const list = res.data.list.records
                    state.orderList = list
                    state.total = res.data.list.total
                })
            }else{

            }
            
        }
        // 邀请好友加入群聊
        const addGroupMembers = () => {
            sessionStorage.setItem('invite_group_id', state.detail.groupId)
            state.inviteFriendBox = true
        }
        // 查看用户信息
        const openUserDetail = (item) => {
            // 启用一个组件框, 即user框数据
            state.user_id = item.userId
            state.showUserDetail = true
        }
        // 订单状态切换
        const orderStatusChange = () => {
            state.page = 1
            loadOrder()
        }
        // 查看订单详情
        const handleOrderDetail = (item) => {
            state.rowForm = item
            state.showOrderDetail = true
        }
        // 页码切换
        const handlePageChange = (e) => {
            state.page = e
            loadOrder()
        }
        // 查看问卷
        const handleQuestionner = e => {
            console.log('问卷')
        }
        // 查看金币订单详情
        const checkDetail = data => {
            state.goldDetail = data
            state.goldOrderDialog = true
        }
        const formateSeconds = computed((item) => {
            return item => {
                return Math.ceil(item / 60)
            }
        })
        // 加载更多商品
        const handleLoadGoods = () => {
            loadGoods()
        }
        // 加载商品
        const loadGoods = () => {
            if(!state.loadMoreGoods) return false
            chatApi.pmsSpuCommentpageList({
                storeId:  params.value.storeId,
                pageNum: state.productPage,
                size: 5,
            }).then((res) => {
                if (res.code == 0) {
                    state.shopList = res.data.products
                    if(res.data.products.length < 5){
                        state.loadMoreGoods = false
                    }else{
                        state.showMoreBtn = true
                    }
                    state.productPage += 1
                }
            }).catch();
        }
        // 发送商品
        const sendGoods = (item) => {
            let order ={
              skuInfos:{
                skuId: item.skuId,
                skuTitle: item.skuTitle,
                skuImage: item.skuImg,
                price: item.skuPrice,
                vipPrice: item.vipPrice,
              }
            }
            chatApi.skuInfo({
              skuInfo:order.skuInfos,
              receiver_id: parseInt(params.value.receiver_id),
              talk_type: parseInt(params.value.talk_type),
              talkSource: params.value.talk_source
            }).then()
        }
        // 付费客服计时
        const timeLoad = () => {
            interver = setInterval(() => {
                state.allSeconds += 1
                const m = parseInt(state.allSeconds / 60)
                const s = state.allSeconds % 60
                state.time = {
                    mm: m < 10 ? '0' + m : m,
                    ss: s < 10 ? '0' + s : s
                }
            }, 1000)
        }
        watch(() => groupId.value,
            val => {
                if(val > 0) {
                    loadGroupDetail()
                    loadMembers()
                    state.page = 1
                    state.status = ''
                }
            }
        )
        onMounted(() => {
            if(parseInt(groupId.value) > 0) {
                loadGroupDetail()
                loadMembers()
                state.page = 1
                state.status = ''
            }
            nextTick(() => {
                if(params.value.customer && params.value.talk_source == '2') {
                    // 客户在商城咨询客服
                    state.activeTab = '0'
                    loadGoods()
                }else if (params.value.customer && params.value.talk_source == '3') {
                    // TO DO 仅作测试用
                    timeLoad()
                }
            })
        })
        onUnmounted(() => {
            clearInterval(interver)
            interver = null
        })
        return {
            ...toRefs(state),
            searchs,
            Search,
            Plus,
            detaultAvatar,
            addGroupMembers,
            openUserDetail,
            getStatusText,
            orderStatusChange,
            handleOrderDetail,
            handlePageChange,
            handleQuestionner,
            checkDetail,
            formateSeconds,
            handleLoadGoods,
            sendGoods
        }
    }
}
</script>

<style lang="scss" scoped>
.container{
    height: 100%;
    overflow: hidden;
    .header {
        height: 60px;
        line-height: 60px;
        padding: 0;
        text-align: center;
        border-bottom: 1px solid #f5eeee;
        position: relative;
        background: var(--next-color-white);
        span {
            font-size: 16px;
            font-weight: 400;
        }
    }
    .main {
        padding: 0;
        .list-item{
            padding: 15px 15px 0;
            .item-tips{
                font-size: 14px;
            }
            .item-data{
                font-size: 13px;
                color: var(--el-text-color-regular);
            }
        }
        .member-box {
            padding: 8px 10px;
            border: 1px solid #ecebeb;
            border-radius: 10px;
            .view-box {
                width: 100%;
                height: 30px;
                margin-top: 5px;
                margin-bottom: 5px;
                position: relative;
                display: flex;
                align-items: center;
                :deep(.el-input) {
                    margin-right: 10px;
                    .el-input__wrapper{
                        box-shadow: var(--el-border-color) 0px 0px 0px 1px;
                    }
                }
                input {
                    width: calc(100% - 40px);
                    height: 30px;
                    line-height: 28px;
                    border-radius: 3px;
                    border: 1px solid #f1e9e9;
                    color: #b3b0b0;
                    font-size: 13px;
                    padding: 0 10px 0 30px;

                    &::-webkit-input-placeholder {
                        color: #ccc9c9;
                        font-size: 13px;
                    }
                }
                .i-sousuo {
                    color: rgb(179, 176, 176);
                    position: absolute;
                    left: 10px;
                    top: 9px;
                }
                span {
                    position: relative;
                    i {
                        font-size: 24px;
                        top: -3px;
                        left: 10px;
                        position: absolute;
                        color: #ccc;
                    }
                }
            }
            .row-header {
                width: 100%;
                height: 30px;
                margin-bottom: 10px;
                border-bottom: 1px solid #e0dddd;
                div {
                    height: 30px;
                    line-height: 30px;
                    &:nth-child(2) {
                        text-align: center;
                    }
                    &:nth-child(3) {
                        text-align: right;
                    }
                }
            }

            .row-items {
                width: 100%;
                height: 30px;
                margin-bottom: 3px;
                font-size: 12px;
                cursor: pointer;
                .row-col{
                    display: flex;
                    align-items: center;
                    .badge {
                        background-color: var(--el-color-primary);
                        color: var(--el-color-primary-light-9);
                        font-size: 12px;
                        font-weight: 400;
                        display: inline-flex;
                        align-items: center;
                        justify-content: center;
                        padding: 0 5px;
                        border-radius: 2px;
                        cursor: default;
                        user-select: none;
                        line-height: 18px;
                        margin-left: 5px;
                        transform-origin: left;
                        flex-shrink: 0;
                        transform: scale(.88);
                    }
                }
                &:hover {
                    background: #f6f6f6;
                }
                div {
                    height: 30px;
                    line-height: 30px;
                    &:nth-child(2) {
                        text-align: center;
                    }
                    &:nth-child(3) {
                        text-align: right;
                    }
                }
                img {
                    display: inline-block;
                    border-radius: 50%;
                    position: relative;
                    top: 4px;
                }
                .nickname {
                    margin-left: 5px;
                    &:hover {
                        color: var(--el-color-primary);
                    }
                }
            }
            .row-list{
                max-height: 100px;
                overflow: auto;
            }
        }
    }
    .order-header{
        padding: 10px 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .order-header-title{
        font-size: 14px;
        color: var(--el-text-color-primary);
    }
    .user-order{
        border: 1px solid #ecebeb;
        border-radius: 10px;
        margin: 0 15px;
        background: var(--next-bg-main-color);
        overflow: auto;
        padding: 5px 2px 0;
        .order-cell{
            padding: 10px 0;
            margin: 0 5px 5px;
            background: var(--next-color-white);
            cursor: pointer;
            transition: .5s;
            border-radius: 10px;
            &:hover{
                box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 12px;
            }
            &:last-child{
                border: none;
            }
            .top-status{
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #ecebeb;
                padding: 0 8px 10px;
                .time{
                    font-size: 13px;
                    color: var(--el-text-color-primary);
                }
                .status{
                    font-size: 13px;
                    &.red{
                        color: var(--el-color-error);
                    }
                }
            }
        }
    }
    .shop-list-item{
        border: 1px solid #ecebeb;
        border-radius: 10px;
        margin: 0 15px;
        overflow: auto;
        padding: 0 10px;
        max-height: 500px;
        .shop-item{
            padding: 15px 0;
            display: flex;
            align-items: stretch;
            border-bottom: 1px solid #ecebeb;
            &:last-child{
                border: none;
            }
            .shop-goods-data{
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                margin-left: 10px;
                flex: 1;
                overflow: hidden;
                .goods-title{
                    font-size: 13px;
                }
                .goods-bottom{
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .price{
                        font-size: 15px;
                        color: var(--el-color-error);
                        .unit{
                            font-size: 12px;
                        }
                    }
                }
            }
        }
    }
    .goods-data{
        padding: 10px 8px 0;
        display: flex;
        justify-content: space-between;
        align-items: stretch;
        .order-data{
            flex: 1;
            overflow: hidden;
            margin-left: 10px;
            display: flex;
            justify-content: space-between;
            flex-direction: column;
            .order-title{
                font-size: 13px;
            }
            .price{
                font-size: 15px;
                color: var(--el-color-error);
                .unit{
                    font-size: 12px;
                }
            }
            .order-bottom{
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }
    }
    .current-preview{
        padding-bottom: 15px;
    }
    .question-cell{
        padding: 10px 0 10px;
        margin: 0 10px 15px;
        border-bottom: 1px solid var(--el-border-color);
        .question-title{
            font-size: 14px;
            cursor: pointer;
            &:hover{
                color: var(--el-color-primary);
            }
        }
    }
    .payGold-cell{
        padding: 10px;
        border-bottom: 1px solid var(--el-border-color);
        position: relative;
        &:last-child{
            border: none;
        }
        .top-status{
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: var(--el-text-color-regular);
            padding-bottom: 5px;
        }
        .order-content{
            padding-bottom: 5px;
            .content-cell{
                font-size: 12px;
                color: var(--el-text-color-primary);
                padding-bottom: 5px;
                &:last-child{
                    padding-bottom: 0;
                }
            }
        }
        .option{
            position: absolute;
            bottom: 10px;
            right: 10px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
.b_row{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
.customer-tabs{
    display: flex;
    width: 100%;
    justify-content: center;
}
.calculate-time{
    padding: 20px 10px;
    height: 80%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .calculate-title{
        text-align: center;
        font-size: 24px;
        color: var(--el-color-primary);
        font-weight: bold;
    }
    .calculate-item{
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        margin: 0 auto;
        width: 220px;
        // height: 280px;
        padding: 0 10px;
        font-size: 36px;
        color: var(--el-text-color-primary);
        span{
            display: block;
            margin-top: -6px;
        }
        .item{
            flex: 1;
            overflow: hidden;
            text-align: center;
        }
    }
    .calculate-progress{
        display: flex;
        justify-content: center;
        margin: 50px auto 0;
    }
}
</style>